package class2;

/**
 * https://leetcode.cn/problems/binary-search/description/
 * 二分查找
 * 在一个有序数组中查找number
 */
public class Code04_BinarySearch {
    public static void main(String[] args) {
        int num = 8;
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        int index = findNumber(arr, 8);
        System.out.println(index);
    }

    public static int findNumber(int[] arr, int num) {
        if (arr == null && arr.length == 0) return -1;
        int L = 0;
        int R = arr.length - 1;

        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (arr[mid] == num) {
                return mid;
            } else if (num > arr[mid]) {
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return -1;
    }
}
